<template>
  <div id="faultTypeDiv">
    <Breadcrumb content="设备类型" />
    <div class="bodyContent">
      <vxe-toolbar perfect ref="toolbarRef">
        <template #buttons>
          <div class="smallToolTitle">设备类型</div>
          <vxe-input style="width: 130px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findFaultTypeList" @keyup="keyupEnter" @search-click="findFaultTypeList"></vxe-input>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findFaultTypeList"></vxe-button>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addFaultType('', '')"></vxe-button>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :loading="saveLoading" @click="saveBatchFaultType"></vxe-button>
        </template>
      </vxe-toolbar>

      <div class="tableBox">
        <vxe-table ref="faultTypeRef"  class="mytable-scrollbar" border="inner" height="auto" :data="faultTypeList" :loading="showLoading" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" :tree-config="{
                expandAll: true,
                transform: true,
                rowField: 'id',
                parentField: 'parentId'
              }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source :reserve="true">
          <vxe-column field="faultTypeCode" title="编码" width="300" tree-node :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input type="text" v-model="row.faultTypeCode"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="faultTypeName" title="名称" width="300" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input type="text" v-model="row.faultTypeName"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="90" align="center" fixed="right">
            <template #default="{ row }">
              <el-tooltip class="item" effect="dark" content="新建子分组" placement="left">
                <vxe-button type="text" status="primary" icon="vxe-icon-square-plus" circle @click="addFaultType(row.id, row)"></vxe-button>
              </el-tooltip>
              <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="deleteFaultType(row)"></vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>

    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '@/stores/store';
// 全局变量定义区 ==========
let store = AppStore();

let showLoading = ref(false); //刷新加载状态
let saveLoading = ref(false); //保存加载状态
let faultTypeList: any = reactive([]); //机构列表数据

// 全局变量定义区 ==========
let searchForm = {
  searchValue: ''
};

// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  findFaultTypeList();
});

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findFaultTypeList();
  }
}
function findFaultTypeList() {
  showLoading.value = true;
  const $table = proxy.$refs.faultTypeRef;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const url = '/api/eq/eqFaultType/findFaultTypeList';
  faultTypeList.length = 0; //放入数据前清空数据
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { searchValue: searchForm.searchValue } })
    .then((res: any) => {
      faultTypeList.push(...res.data);
      $table.setAllTreeExpand(true);
      // $table.loadData(faultTypeList, true);
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}

// 新建一级机构/子结构
async function addFaultType(parentids: any, row: any): Promise<void> {
  //clearForm();
  const $table = proxy.$refs.faultTypeRef;
  if ($table) {
    // 获取新增的数据记录
    const record = {
      faultTypeCode: '',
      faultTypeName: '',
      parentId: parentids != '' || parentids != null ? parentids : null,
      id: '',
      seq: faultTypeList.length + 1
    };

    const { row: newRow } = await $table.insertAt(record, -1);
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); // 新建一行空数据时展开这一栏
    }
  }
}

async function saveBatchFaultType() {
  let $Xtable = proxy.$refs.faultTypeRef;
  if ($Xtable) {
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    $Xtable.setAllRowExpand(true);
    $Xtable.setAllTreeExpand(true);
    console.log(updateRecords);
    console.log(InsertRecords);

    const editFaultTypes = [] as any[];
    updateRecords.forEach((e: any) => {
      const iISample: any = {
        id: e.id,
        faultTypeCode: e.faultTypeCode,
        faultTypeName: e.faultTypeName,
        parentId: e.parentId,
        seq: e.seq
      };

      editFaultTypes.push(iISample);
    });
    InsertRecords.forEach((e: any) => {
      const iISample: any = {
        id: e.id,
        faultTypeCode: e.faultTypeCode,
        faultTypeName: e.faultTypeName,
        parentId: e.parentId,
        seq: e.seq
      };
      editFaultTypes.push(iISample);
    });

    if (editFaultTypes.length > 0) {
      const url = '/api/eq/eqFaultType/saveOrUpdateFaultType';
      const obj: any = {};
      obj.faultTypeList = editFaultTypes;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);

          proxy.$nextTick(() => {
            findFaultTypeList();
          });
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}

// 删除机构
function deleteFaultType(row: any) {
  let $table = proxy.$refs.faultTypeRef;

  $table.setAllTreeExpand(true);
  $table.setAllRowExpand(true);
  proxy
    .$confirm('确定删除此设备？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/eq/eqFaultType/deleteFaultType';
      if (row.id) {
        proxy.$http.post(url, row).then((res: any) => {
          if (res.status.code === 400) {
            VxeMessage('删除失败', VxeNotifyType.error);
          } else {
            VxeMessage('删除成功', VxeNotifyType.success);
          }
          findFaultTypeList();
          $table.setAllTreeExpand(true);
        });
      } else {
        if ($table) {
          await $table.remove(row);
          VxeMessage('删除成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
</script>

<style lang="scss" scoped>
#faultTypeDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }

    // 机构表格
    :deep(.vxe-table--render-default) {
      height: 100%;
    }
    :deep(.vxe-table--render-wrapper) {
      height: 100%;
      background-color: $base-white;
    }
    .tableBox {
      height: calc(100% - 39px);
    }
  }
}
</style>
